package spynx.desl.runtime.matchinfos.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import spynx.desl.Argument;
import spynx.desl.Element;
import spynx.util.ArgumentSet;
import spynx.util.DeslRuntimeUtil;
import spynx.util.PatternMismatchedException;

public class DataPartMatchInfo extends PatternMatchInfo {

	private ArgumentSet fields;
	private Matcher matcher;

	public DataPartMatchInfo() {

	}
	
	@Override
	public void intialize() {
		super.intialize();
		ArgumentSet args =  getArguments(); //  new ArgumentSet(getPattern().getArguments());
		
		String strPattern = args.getArgument(getContext(), 0, "");
		int flag = args.getArgument(getContext(), "flag", Pattern.MULTILINE);
		
		if (strPattern != null && strPattern.length() > 0)
			match(strPattern, flag, true);
		
		Argument groupArg = args.getArgumentObject("groups");
		if (groupArg != null)
			fields = new ArgumentSet(((Element) groupArg).getChildren(Argument.class));
	}

	public void match(String pattern, int flag, boolean updatePosition) {
		Pattern regex = DeslRuntimeUtil.compilePattern(getContext(), pattern, flag);
		matcher = regex.matcher(getLocalInput());
		if (!matcher.find())
			throw new PatternMismatchedException(String.format("Unable to match '%s'", pattern));
		
		if (updatePosition) {
			setEndLocation(matcher.end() + getBeginLocation());
			setBeginLocation(matcher.start() + getBeginLocation());
		}
	}

	@Override
	public boolean hasFieldname(String fieldname) {
		if (fields != null && fields.getArgumentObject(fieldname) != null)
			return true;
		return super.hasFieldname(fieldname);
	}
	
	@Override
	public Object get(String fieldname) {
		if (!isMatched())
			throw new RuntimeException(String.format("Pattern '%s' is not matched", getPattern().getName()));
		
		if (fields != null) {
			int idx = fields.getArgument(getContext(), fieldname, -1);
			if (idx >= 0)
				return get(idx);
		}
		return super.get(fieldname);
	}
	
	@Override
	protected Object get(int index) {
		if (!isMatched())
			throw new RuntimeException(String.format("Pattern '%s' is not matched", getPattern().getName()));
		return matcher.group(index);
	}
}
